#include "appsetting.h"
#include "ydexception.h"
#include <QApplication>
#include <QFile>
#include <QStringList>
#include <QDebug>

YDAppSettings::YDAppSettings(QObject *parent) :
    QObject(parent) {
    QString fileName = qApp->applicationDirPath() + "/settings.txt";
    qDebug() << fileName;
    QFile file(fileName);

    if (!file.open(QIODevice::ReadOnly)) {
        throw YDException("配置文件不正确");
    }

    QByteArray raw = file.readAll();
    QString data = QString::fromUtf8(raw);

    qDebug() << raw;
    qDebug() << data;
    if (data.isEmpty()) {
        file.close();
        throw YDException("配置文件不正确");
    }

    data = data.replace("\r\n", "\n").replace("\n\r", "\n").replace(" ", "");
    QStringList lines = data.split("\n");

    if (lines.isEmpty()) {
        file.close();
        throw YDException("配置文件不正确");
    }

    for (auto s : lines) {
        if (s.indexOf("\"") != 0) {
            // 非注释部分
            QStringList kv = s.split("=");

            if (kv.size() != 2) {
                continue;
            }

            QString key = *kv.begin();
            QString value = *(kv.begin()++);
            this->settingMap[key] = value;
        }
    }

    file.close();
}

QString YDAppSettings::get(const QString& key) {
    map_t::iterator it = this->settingMap.find(key);

    if (it != this->settingMap.end()) {
        return it->second;
    } else {
        return "";
    }
}

void YDAppSettings::set(const QString& key, const QString& value) {
    this->settingMap[key] = value;

    QString fileName = qApp->applicationDirPath() + "/setting.txt";
    QFile file(fileName);

    if (file.open(QIODevice::WriteOnly)) {
        for (map_t::iterator it = this->settingMap.begin(); it != this->settingMap.end(); it++) {
            QString line = it->first + "=" + it->second + "\n";
            file.write(line.toUtf8());
        }

        file.close();
    }

    emit this->sigValueChanged(key, value);
}
